<!--
  * 陈列协议
  *
-->
<template>
  <!---------- 查询表单form begin ----------->
  <a-card size="small" :bordered="false" :hoverable="false" class="query-form-wrapper smart-margin-bottom10 smart-radius-2">
    <a-form>
      <a-row :gutter="[8, 10]">
        <a-col :span="5.5">
          <a-form-item label="日期" class="smart-margin-bottom0">
            <custom-range-picker v-model:value="fromData.create_time" />
          </a-form-item>
        </a-col>
        <a-col :span="3.5">
          <a-form-item label="陈列协议" class="smart-margin-bottom0">
            <a-input v-model:value.trim="fromData.agreement_name" placeholder="陈列协议" allow-clear />
          </a-form-item>
        </a-col>
        <a-col :span="3">
          <a-form-item label="门店名称" class="smart-margin-bottom0">
            <Select name="Store" v-model:value="fromData.store_id" placeholder="请选择门店" @search="onSearch" />
          </a-form-item>
        </a-col>
        <!-- <a-col :span="3">
          <a-form-item label="陈列周期" class="smart-margin-bottom0">
            <EnumSelect enum-name="DISPLAY_STATUS_ENUM" v-model:value="queryForm.display_cycle" placeholder="陈列周期" @submit="onSearch" />
          </a-form-item>
        </a-col> -->
        <!-- <a-col :span="3">
          <a-form-item label="兑换年份" class="smart-margin-bottom0">
            <EnumSelect enum-name="DISPLAY_STATUS_ENUM" v-model:value="queryForm.purchase_status" placeholder="兑换年份" @submit="onSearch" />
          </a-form-item>
        </a-col> -->
        <a-col :span="5">
          <a-button-group>
            <a-button type="primary" html-type="submit" @click="onSearch" v-privilege="'goods:query'">
              <template #icon>
                <SearchOutlined />
              </template>
              查询
            </a-button>
            <a-button @click="resetQueryData" v-privilege="'goods:query'">
              <template #icon>
                <ReloadOutlined />
              </template>
              重置
            </a-button>
          </a-button-group>
        </a-col>
      </a-row>
    </a-form>
  </a-card>
  <!---------- 查询表单form end ----------->

  <a-card size="small" :bordered="false" :hoverable="true" class="query-table-wrapper">
    <!---------- 表格操作行 begin ----------->
    <a-row class="smart-table-btn-block">
      <div class="smart-table-operate-block">
        <!-- <a-button @click="deleteData(selectedRowKeyList)" danger :disabled="selectedRowKeyList.length === 0" v-privilege="'goods:batchDelete'">
          <template #icon>
            <DeleteOutlined />
          </template>
          批量删除
        </a-button>

        <a-button @click="onExportGoods" type="primary" v-privilege="'goods:exportGoods'">
          <template #icon>
            <ExportOutlined />
          </template>
          导出
        </a-button> -->
      </div>
      <div class="smart-table-setting-block">
        <TableOperator v-model="columns" :tableId="TABLE_ID_CONST.BUSINESS.ERP.GOODS" :refresh="queryData" />
      </div>
    </a-row>
    <!---------- 表格操作行 end ----------->
    <div class="table-wrapper">
      <a-table size="small" :dataSource="tableData" :columns="columns" :loading="tableLoading" rowKey="id" bordered :scroll="{ x: 'max-content', y: tableScrollY }" :pagination="false" :showSorterTooltip="false" :row-selection="{ fixed: true, selectedRowKeys: selectedRowKeyList, onChange: onSelectChange }">
        <template #bodyCell="{ text, record, column }">
          <template v-if="column.dataIndex === 'type'">
            <span v-if="text == 2">{{ record.name }}</span>
            <span v-else>{{ PROGRESS_STATUS_ENUM[text] }}</span>
          </template>
          <template v-if="column.dataIndex === 'purchase_status'">
            <a-tag :color="TagColor[text]">{{ getDescByValue('APPROVAL_STA_ENUM', Number(text)) }}</a-tag>
          </template>
        </template>
      </a-table>
    </div>
    <div class="smart-query-table-page query-table-page">
      <a-pagination showSizeChanger showQuickJumper show-less-items :pageSizeOptions="PAGE_SIZE_OPTIONS" :defaultPageSize="queryForm.limit" v-model:current="queryForm.page" v-model:pageSize="queryForm.limit" :total="total" @change="queryData" @showSizeChange="queryData" :show-total="(total) => `共${total}条`" />
    </div>
  </a-card>
</template>
<script setup lang="ts">
import CustomRangePicker from '@/components/business/custom-range-picker/index.vue'
import { message, Modal } from 'ant-design-vue'
import Select from '@/components/business/select/index.vue'
import { useLoadingStore } from '@/store/modules/loading-store'
import { errorSentry } from '@/lib/error-sentry'
import { displayApi } from '@/api/business/marketing/display-api'
import { PAGE_SIZE_OPTIONS, DEFAULT_TIME_RANGE } from '@/constants/system/common-const'
import TableOperator from '@/components/support/table-operator/index.vue'
import { TABLE_ID_CONST } from '@/constants/support/table-id-const'
import EnumSelect from '@/components/framework/enum-select/index.vue'
import { useQuery } from '@/hooks/web/use-query-hook'
import { QUERY_FORM_OP } from '@/constants/support/query-form-op-const'
import { ORDER_TYPE_ENUM } from '@/constants/business/orders-const'
import { useEnums } from '@/hooks/plugins/useEnums'
import { useAppConfigStore } from '@/store/modules/app-store'
import { useResize } from '@/hooks/web/use-resize-hook'
import { WAREHOUSE_TYPE, WAREHOUSE_ATTRIBUTE_TYPE } from '@/constants/business/storage/warehouse/warehouse-const'
const appConfigStore = useAppConfigStore()
const loadingStore = useLoadingStore()
const { getDescByValue } = useEnums()
// ----------------------------- tag单据状态 -----------------------------
const enum PROGRESS_STATUS_ENUM {
  '现金' = 1,
  '商品'
}
enum TagColor {
  'processing' = 1,
  'success',
  'orange',
  'error',
  'warning'
}

// ----------------------------- 计算表格高度 -----------------------------
const { tableScrollY } = useResize()

// ---------------------------- 表格列 ----------------------------
const columns = computed(() => [
  {
    title: '陈列协议编号',
    dataIndex: ['agreement', 'agreement_no'],
    width: appConfigStore.$state.compactFlag ? 170 : 210
  },
  {
    title: '协议名称',
    dataIndex: ['agreement', 'agreement_name']
  },
  {
    title: '备注',
    dataIndex: ['agreement', 'content']
  },
  {
    title: '门店名称',
    dataIndex: ['agreement', 'store', 'store_name']
  },
  {
    title: '门店编号',
    dataIndex: ['agreement', 'store', 'store_no']
  },
  {
    title: '商品/现金',
    dataIndex: 'type'
  },
  {
    title: '单位',
    dataIndex: 'unit'
  },
  {
    title: '陈列时段',
    dataIndex: ['agreement', 'display_cycle']
  },
  {
    title: '总计',
    dataIndex: ''
  },
  {
    title: '1月',
    dataIndex: ''
  },
  {
    title: '2月',
    dataIndex: ''
  },
  {
    title: '3月',
    dataIndex: ''
  },
  {
    title: '4月',
    dataIndex: ''
  },
  {
    title: '5月',
    dataIndex: ''
  },
  {
    title: '6月',
    dataIndex: ''
  },
  {
    title: '7月',
    dataIndex: ''
  },
  {
    title: '8月',
    dataIndex: ''
  },
  {
    title: '9月',
    dataIndex: ''
  },
  {
    title: '10月',
    dataIndex: ''
  },
  {
    title: '11月',
    dataIndex: ''
  },
  {
    title: '12月',
    dataIndex: ''
  }
])

// ---------------------------- 查询数据表单和方法 ----------------------------
const fromData = ref({
  create_time: DEFAULT_TIME_RANGE.value,
  agreement_name: '',
  store_id: undefined,
  display_cycle: undefined
})
const total_amount = ref({
  total_detail_sum: 0
})
const { queryForm, tableData, tableLoading, total, resetQuery, onSearch, queryData, deleteData } = useQuery({
  fetchDataApi: async (params) => {
    const dataList = {
      ...params,
      ...fromData.value
    }
    const res = await displayApi.agreementDetailsList(dataList)
    const { data, ...other } = res.data
    total_amount.value = {
      ...other
    }
    return {
      list: res.data.data,
      total: res.data.total
    }
  },
  queryFormFilter: {},
  queryFormOp: {}
})

onActivated(queryData)
const resetQueryData = () => {
  fromData.value.create_time = DEFAULT_TIME_RANGE.value
  fromData.value.agreement_name = ''
  fromData.value.store_id = undefined
  fromData.value.display_cycle = undefined
  resetQuery()
}
// Select查询参数
const selectFetchParams = {
  warehouse: {
    filter: {
      warehouse_type: WAREHOUSE_TYPE.FIXED.value,
      attribute_type: WAREHOUSE_ATTRIBUTE_TYPE.WAREHOUSE.value
    },
    op: {
      warehouse_type: QUERY_FORM_OP['全等查询'],
      attribute_type: QUERY_FORM_OP['全等查询']
    },
    fields: 'id,name'
  }
}

// ---------------------------- 添加/修改 ----------------------------
const formModal = ref()

function showForm(rowData) {
  formModal.value.showDrawer(rowData)
}

// ---------------------------- 详情 ----------------------------
const detailRef = ref()

const detail = (rowData) => {
  detailRef.value.showDrawer(rowData)
}

// ---------------------------- 打印 ----------------------------
const printRef = ref()

const print = (goodsData) => {
  printRef.value.showDrawer(goodsData)
}

// 选择表格行
const selectedRowKeyList = ref([])

function onSelectChange(selectedRowKeys) {
  selectedRowKeyList.value = selectedRowKeys
}
// ---------------------------- 审核/驳回 ----------------------------

// 审核
function returnBack(rowData) {
  Modal.confirm({
    title: '提示',
    content: '确定要审核【' + rowData.no + '】吗?',
    okText: '审核',
    okType: 'danger',
    onOk() {
      singleDelete(rowData)
    },
    cancelText: '取消',
    onCancel() {}
  })
}

async function singleDelete(rowData) {
  try {
    loadingStore.show()
    const res = await purchaseOrderApi.modify({ id: rowData.id, field: 'purchase_status', value: 2 })
    message.success(res.msg)
    queryData()
  } catch (e) {
    message.error(e.msg)
    errorSentry.captureError(e)
  } finally {
    loadingStore.hide()
  }
}

// 驳回
function modifyAction(rowData) {
  Modal.confirm({
    title: '提示',
    content: '确定要驳回【' + rowData.no + '】吗?',
    okText: '驳回',
    okType: 'danger',
    onOk() {
      singleDeleteAction(rowData)
    },
    cancelText: '取消',
    onCancel() {}
  })
}

async function singleDeleteAction(rowData) {
  try {
    loadingStore.show()
    const res = await purchaseOrderApi.modify({ id: rowData.id, field: 'purchase_status', value: 4 })
    message.success(res.msg)
    queryData()
  } catch (e) {
    message.error(e.msg)
    errorSentry.captureError(e)
  } finally {
    loadingStore.hide()
  }
}
// ------------------------------- 订单类型去重 ---------------------------------
const uniqueTypes = (detailList) => {
  // 使用 Set 去重
  const types = new Set(detailList.map((item) => item.type))
  return Array.from(types) // 将 Set 转换为数组
}

const uniqueTypesUnit = (detailList) => {
  // 使用 Set 去重
  const types = new Set(detailList.map((item) => item.unit))
  return Array.from(types) // 将 Set 转换为数组
}
</script>
